import tkinter as tk
from tkinter import ttk
import mysql.connector

def query_database():
    query = query_entry.get("1.0", tk.END).strip()
    if query:
        try:
            # 连接数据库
            mydb = mysql.connector.connect(
                host="localhost",
                user="root",
                password="1234Qwer",
                database="hmdb"
            )
            mycursor = mydb.cursor()

            # 执行查询
            mycursor.execute(query)
            results = mycursor.fetchall()

            # 获取列名
            columns = [desc[0] for desc in mycursor.description]

            # 清空之前的结果
            for item in tree.get_children():
                tree.delete(item)

            # 插入列名
            tree["columns"] = columns
            for col in columns:
                tree.heading(col, text=col)
                tree.column(col, width=150)  # 设置列宽

            # 插入数据行
            for row in results:
                tree.insert("", tk.END, values=row)

            # 提交事务（如果查询不涉及修改数据，这一步不是必需的，但为了完整性包含在这里）
            mydb.commit()
        except mysql.connector.Error as err:
            # 创建新的对话框窗口显示错误信息
            error_window = tk.Toplevel(root)
            error_window.geometry("800x600")
            error_label = tk.Label(error_window, text=f"查询失败: {err}")
            error_label.pack()
        finally:
            # 关闭数据库连接
            mydb.close()
    else:
        # 创建新的对话框窗口显示提示信息
        info_window = tk.Toplevel(root)
        info_window.geometry("800x600")
        info_label = tk.Label(info_window, text="请输入查询语句。")
        info_label.pack()

root = tk.Tk()
root.geometry("800x500")  # 设置初始界面大小为1000*960
root.title("数据库查询界面")

# 创建查询界面框架并设置大小为800*300
query_frame = tk.Frame(root, width=800, height=300)
query_frame.pack(pady=10)

# 查询语句输入框
query_label = tk.Label(query_frame, text="请输入查询语句:")
query_label.pack()
query_entry = tk.Text(query_frame, height=5)
query_entry.pack()

# 执行查询按钮
query_button = tk.Button(query_frame, text="执行查询", command=query_database)
query_button.pack()

# 创建结果显示界面框架并设置大小为800*600
result_frame = tk.Frame(root, width=800, height=600)
result_frame.pack(pady=10)

# 结果显示 Treeview
tree = ttk.Treeview(result_frame)
# 设置列宽（假设列名已知，可根据实际情况调整）
columns = ["Column1", "Column2", "Column3"]  # 替换为实际的列名
tree["columns"] = columns
for col in columns:
    tree.heading(col, text=col)
    tree.column(col, width=115)

# 添加滚动条（可选，如果需要）
scrollbar = ttk.Scrollbar(result_frame, orient="vertical", command=tree.yview)
tree.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right", fill="y")
tree.pack(side="left", fill="both", expand=True)
vbar = ttk.Scrollbar(result_frame, orient="vertical", command=tree.yview)
vbar.pack(side="bottom", fill="x")
tree.configure(yscrollcommand=vbar.set)
def on_treeview_configure(event):
    tree.configure(scrollregion=tree.bbox("all"))
tree.bind("<Configure>", on_treeview_configure)
root.mainloop()